import datetime
from PyQt5.QtWidgets import QWidget, QCompleter, QTableWidgetItem
from PyQt5.QtCore import QDateTime, QDate, QTime,Qt
from qfluentwidgets import InfoBarPosition, InfoBar
from ui.create_time_ui import Ui_creat_time
from src.db_utils import *
from dateutil.relativedelta import relativedelta

class creat_time_cls(Ui_creat_time,QWidget):

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)
        self.user_data = []
        self.db = Database()
        self.init_datetime()
        self.combox_init()
        self.add_work_time.clicked.connect(self.create_work_time)
        self.ticket_show.clicked.connect(self.show_ticket)

    def combox_init(self):
        self.init_combo_box(self.is_worktime, ['工单', '其他', '培训', '会议', '渠道支持', '竞品分析', '市场活动', '项目'])
        self.init_choose_index()
          
    def init_combo_box(self, combobox, items):
        combobox.setCurrentIndex(-1)
        combobox.addItems(items)

    def init_choose_index(self):
        self.custom_department.setVisible(False)  # 隐藏按钮
        self.label_depart.setVisible(False)
        self.is_worktime.currentIndexChanged.connect(self.on_worktime_changed)

    def on_worktime_changed(self, index):
        if index == 0:  # 当选择了第二个选项时
            self.custom_department.setVisible(False)  # 隐藏按钮
            self.label_depart.setVisible(False)
        else:
            self.custom_department.setVisible(True)  # 显示按钮
            self.label_depart.setVisible(True)

    def init_datetime(self):
        db = Database()
        result = db.get_data_from_db("SELECT default_time FROM default_set")
        time = QTime.fromString(result[0], 'hh:mm:ss')
        datetime = QDateTime(QDate.currentDate(), time)
        self.dateTimeEdit.setDateTime(datetime)

    def data_clear(self):
        # self.ticket_id.clear()
        self.work_contect.clear()
        self.use_time.clear()
    
    def create_work_time(self):
        db = Database()
        c = db.get_connection()

        ticket_id = self.ticket_id.text()
        custom_department = self.custom_department.text()
        work_contect = self.work_contect.toPlainText()
        
        # 时间计算
        # use_time = float(self.use_time.text())
        time_text = self.use_time.text()
        if time_text.isdigit():  # 检查输入是否为整数
            use_time = int(time_text)  # 将文本转换为整数
        else:
            use_time = float(time_text)  # 将文本转换为浮点数
        start_time = self.dateTimeEdit.dateTime().toPyDateTime()  # 获取开始时间
        lunch_break = datetime.timedelta(hours=1)
        def_time = db.get_data_from_db("SELECT default_time FROM default_set")
        time = QTime.fromString(def_time[0], 'hh:mm:ss')
        default_time = QDateTime(QDate.currentDate(), time)
        if default_time.time() == datetime.time(8, 30):
            lunch_start_time = datetime.datetime.combine(start_time.date(), datetime.time(12, 0))
        elif default_time.time() == datetime.time(9, 0):
            lunch_start_time = datetime.datetime.combine(start_time.date(), datetime.time(12, 0))
        elif default_time.time() == datetime.time(9, 30):
            lunch_start_time = datetime.datetime.combine(start_time.date(), datetime.time(13, 0))
        elif default_time.time() == datetime.time(10, 0):
            lunch_start_time = datetime.datetime.combine(start_time.date(), datetime.time(13, 30))
        
        if start_time.time() < lunch_start_time.time():
            end_time = start_time + datetime.timedelta(hours=use_time)
            if end_time.time() < lunch_start_time.time():
                my_time = end_time
            elif end_time.time() >= lunch_start_time.time():
                my_time = end_time + lunch_break
        else:
            end_time = start_time + datetime.timedelta(hours=use_time)
            my_time = end_time

        c.execute("SELECT ticket_code FROM ticket WHERE id = ? ", (ticket_id,))
        result = c.fetchone()
        if result is not None:
            ticket_code = result[0]
        else:
            ticket_code = None
        is_worktime = self.is_worktime.currentText()

        valid_worktimes = ['其他', '培训', '会议', '渠道支持', '竞品分析', '市场活动']

        if not work_contect  or not use_time or use_time == '' :
            InfoBar.warning(title='警告',content="工时内容及时间没写，无法插入数据！",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=2000,parent=self)
            return
        if not ticket_id and is_worktime == '工单' :
            InfoBar.warning(title='警告',content="此工单工时没写工单编号，无法插入数据！",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=2000,parent=self)
            return
        if is_worktime == '工单' :
            InfoBar.warning(title='警告',content="这单子是工单工时",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_RIGHT,duration=4000,parent=self)
        elif is_worktime in valid_worktimes :
            InfoBar.warning(title='警告',content="这单子是部门工时",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP_LEFT,duration=4000,parent=self)
        elif is_worktime == '项目' :
            InfoBar.warning(title='警告',content="这单子是项目工时",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.BOTTOM,duration=4000,parent=self)


        self.user_data.append((is_worktime, ticket_code, work_contect, use_time, start_time, end_time, ticket_id,custom_department))
        c.execute('''CREATE TABLE IF NOT EXISTS ticket_time
                    (id INTEGER PRIMARY KEY AUTOINCREMENT, is_worktime INTEGER, ticket_code INTEGER, work_contect TEXT, use_time TEXT, start_time DATETIME, end_time DATETIME, ticket_id INTEGER, custom_department TEXT)''')
        
        for data in self.user_data:
            c.execute("INSERT INTO ticket_time (is_worktime , ticket_code, work_contect, use_time, start_time, end_time, ticket_id , custom_department) "
                        " VALUES (?, ?, ?, ?, ?, ?, ?, ?)", data)

        db.close_connection()

        InfoBar.success(title='工单添加',content="成功",orient=Qt.Horizontal,isClosable=True,position=InfoBarPosition.TOP,duration=2000,parent=self)
        self.data_clear()
        self.user_data = []
        self.dateTimeEdit.setDateTime(my_time)

    def show_ticket(self):
        db = Database()
        c = db.get_connection()
        
        self.TableWidget.clearContents()
        self.TableWidget.verticalHeader().hide()
        self.TableWidget.resizeRowsToContents()
        self.TableWidget.setHorizontalHeaderLabels(['开始时间','结束时间', '本地工单id', '工单编号', '用时','姓名', '工单标题','工单状态','问题','部门'])
        
        ticket_query = ("SELECT start_time, end_time,id, ticket_code, use_time, custom_name, ticket_title, column_ticket_status, question_ask,custom_department "
                " FROM ticket WHERE (column_ticket_status LIKE '%已开启%' or column_ticket_status LIKE '%待回应%') AND (is_del <> '1' OR is_del is null)"
                " ORDER BY start_time DESC")
        c.execute(ticket_query)

        ticket_sheet = c.fetchall()
        for i, integrator in enumerate(ticket_sheet):
            for j in range(0,10):
                value = integrator[j]
                str_tab = str(value) if value is not None else ''
                self.TableWidget.setItem(i, j, QTableWidgetItem(str_tab))
        self.TableWidget.resizeColumnsToContents()

